# -*- coding=utf8 -*-
import tornado.httpserver
import os
import datetime
import time
import json
import tornado.ioloop
import tornado.options
import tornado.web
from models.Item import Item, Session, text
import base64


class FindItemHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', friendly user!')

    def post(self):
        ItemO = json.loads(self.request.body)
        session = Session()
        clew = ItemO['clew']
        NameClew = 'instr(name,clew) or instr(clew,name)'
        AttrClew = 'instr(attr,clew) or instr(clew,attr)'
        try:
            if abs(float(clew)) > 0.01:
                PriceClew = ' or abs(price - clew) <50 '
            else:
                PriceClew = ""
        except:
            PriceClew = ''

        PositionClew = 'instr(position,clew) or instr(clew,position)'
        Filter_str = NameClew + ' or ' + AttrClew + PriceClew + ' or ' + PositionClew
        Filter_str = Filter_str.replace('clew', "'" + clew + "'")
        items = session.query(Item).filter(text(Filter_str)).order_by(Item.created_date.desc()).all()
        ret = {'code': 0, 'desc': '查询成功', 'data': []}
        for i in items:
            o = dict()
            o['id']   = i.id
            o['name'] = i.name
            o['attr'] = i.attr
            o['position'] = i.position
            o['pic'] = i.pic
            o['updateTime'] = str(i.created_date)
            ret['data'].append(o)
        self.write(json.dumps(ret))
        pass
